<?php
class Reviews extends CActiveRecord {
    
    public $revId;
    public $userId;
    public $partnerid;
    public $date;
    public $text;
    public $title;
    public $exp;
    public $isAnonym;
    public $redactorNotice;
    public $status;
    public $averageRating = 0;
    public $userIp;
    public $url;
    
    public $ratings;
    public $aditionalRatings;
    public $anonymImg;
    public $deletedImg;
    public $textScore;
    
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function tableName() {
        return 'reviews';
    }
    
    public function attributeLabels() {
        return array(
            'text' => 'Текст отзыва',
            'title' => 'Заголовок отзыва',
            'exp' => 'Опыт работы с партнеркой',
            'status' => 'Статус отзыва',
            'redactorNotice' => 'Заметка редактора'
        );
    }
    
    public function rules() {
        return array(
            array('title, ratings, partnerid, anonymImg, isAnonym, averageRating, deletedImg, exp, redactorNotice, status, textScore, aditionalRatings', 'safe'),
            array('text', 'required', 'message'=>'{attribute} не может быть пустым'),
            array('ratings', 'required', 'message'=>'Вы должны поставить минимум 1 оценку'),
            array('title, redactorNotice', 'filter', 'filter'=>'strip_tags'),
            array('textScore', 'stripTags'),
        );
    }
    
    public function stripTags($attribute,$params) {
        if(!empty($this->textScore)) {
            foreach($this->textScore as $k=>$v) 
                $this->textScore[$k] = strip_tags($this->textScore[$k]);
        }
    }
    
    public function relations() {
        return array(
            'user'=>array(self::BELONGS_TO, 'User', array('userId'=>'userid')),
            'revRatings'=>array(self::HAS_MANY, 'ReviewsRatings', 'revId'),
            'images'=>array(self::HAS_MANY, 'Images', 'revId'),
            'partner'=>array(self::BELONGS_TO, 'Partner', 'partnerid'),
            'comments'=>array(self::HAS_MANY, 'Comments', array('typeId'=>'revId'), 'on'=>'comments.type="review"')
        );
    }
    
    public function beforeSave() {
        if(!parent::beforeSave()) return false;
        if($this->getScenario() != 'update') {
            $this->date = time();
            $this->userId = Yii::app()->user->getId();
        }
        $this->averageRating = 0;
        if(!empty($this->ratings)) {
            foreach ($this->ratings as $key => $value) 
                $this->averageRating += $value;
            $this->averageRating /= count($this->ratings);
        }
        $this->userIp = Yii::app()->request->userHostAddress;
        #Если урл длиннее 3 символов пишем его странслит в качестве урл. 
        //Если такой урл уже есть добавляем 1, или другую цифру. Если меньше 3 символов в урл идет ИД(см afterSave()). 
        if(mb_strlen($this->title, 'utf-8') >= 3) {
            $url = CPartnerkiHelper::toTranslit(mb_strtolower($this->title, 'UTF-8'));
            $urls = Yii::app()->db->createCommand()->select('url')->from('reviews')->where('url like "%'.$url.'_%" or url="'.$url.'"')->order('url asc')->queryAll();
            if(empty($urls)) {
                $this->url = $url;
            } else {
                $res = array();
                foreach ($urls as $u) $res[] = $u['url']; 
                if(!in_array($url, $res)) {
                    $this->url = $url;
                } else {
                    if(!$this->getIsNewRecord() && $this->url == $url) {
                        
                    } else {
                        $i=1;
                        while (1) {
                            if(!in_array($url.'_'.$i, $res)) {
                                $this->url = $url.'_'.$i;
                                break;
                            }
                            $i++;
                        }
                    }
                }
            }
        }
        return true;
    }
   
    public function afterSave() {
        if($this->getScenario() == 'update') {
            Yii::app()->db->createCommand()->delete('reviews_ratings', 'revId=:id', array(':id'=>$this->primaryKey));
            if(!empty($this->deletedImg)) {
                $this->deletedImg = explode(',', $this->deletedImg);
                for($i=0; $i<count($this->deletedImg); $i++) {
                    Yii::app()->db->createCommand()->delete('reviews_images', '`smallImg`="'.$this->deletedImg[$i].'"');
                    if(file_exists($_SERVER['DOCUMENT_ROOT'].'/images/uploads/reviews/'.$this->deletedImg[$i]))
                        unlink($_SERVER['DOCUMENT_ROOT'].'/images/uploads/reviews/'.$this->deletedImg[$i]);
                    if(file_exists($_SERVER['DOCUMENT_ROOT'].'/images/uploads/reviews/'.str_replace('sm', '', $this->deletedImg[$i])))
                        unlink($_SERVER['DOCUMENT_ROOT'].'/images/uploads/reviews/'.str_replace('sm', '', $this->deletedImg[$i]));
                }
            }
            Yii::app()->db->createCommand()->delete('reviews_text_ratings', 'revId=:id', array(':id'=>$this->primaryKey));
        }
        if(!empty($this->ratings)) {
            if(!empty($this->aditionalRatings)) $this->ratings = CMap::mergeArray($this->ratings, $this->aditionalRatings);
            foreach ($this->ratings as $key => $value) {
                Yii::app()->db->createCommand()->insert('reviews_ratings', array('revId'=>$this->primaryKey, 'type'=>$key, 'val'=>$value, 'partnerId'=>$this->partnerid));
            }
        }
        $userFiles = Yii::app()->user->getState('xuploadFiles', array());
        if(!empty($userFiles)) {
            foreach ($userFiles as $k=>$v) {
                $this->changeImage($k);                    
                Yii::app()->db->createCommand()->update('reviews_images', array('revId'=>$this->primaryKey, 'smallImg'=>'sm'.$k, 'onlyModerator'=>isset($this->anonymImg[$k]) ? $this->anonymImg[$k] : 0 ), 'bigImg = :bigName', array(':bigName'=>$k));
            }
        }
        if(!empty($this->textScore)) {
            foreach ($this->textScore as $k=>$v) {
                if(empty($v)) continue;
                Yii::app()->db->createCommand()->insert('reviews_text_ratings', array('scoreId'=>$k, 'val'=>$v, 'revId'=>$this->primaryKey));
            }
        }
        if(mb_strlen($this->title, 'utf-8') < 3) {
            Yii::app()->db->createCommand()->update('reviews', array('url'=>$this->primaryKey), 'revId='.$this->primaryKey);
            $this->url = $this->primaryKey;
        } 
    }
    
    private function changeImage($img) {
        if(!file_exists($_SERVER['DOCUMENT_ROOT'].'/images/uploads/reviews/'.$img)) return 0;
        Yii::app()->ih->load($_SERVER['DOCUMENT_ROOT'].'/images/uploads/reviews/'.$img)->watermark($_SERVER['DOCUMENT_ROOT'] . '/images/prettyImg/watermark.png', 10, 20, CImageHandler::CORNER_CENTER, 0.3)->save($_SERVER['DOCUMENT_ROOT'].'/images/uploads/reviews/'.$img);
        Yii::app()->ih->load($_SERVER['DOCUMENT_ROOT'].'/images/uploads/reviews/'.$img)->resize(80, 80)->save($_SERVER['DOCUMENT_ROOT'].'/images/uploads/reviews/sm'.$img);
    }
    
    public function beforeDelete() {
        if(!parent::beforeDelete()) return false;
        Yii::app()->db->createCommand()->delete('reviews_ratings', 'revId='.$this->primaryKey);
        Yii::app()->db->createCommand()->delete('reviews_images', 'revId='.$this->primaryKey);
        return true;
    }
    
    public function pagination($limit, $offset) {
        $this->getDbCriteria()->mergeWith(array('offset'=>$offset,'limit'=>$limit));
        return $this;
    }
}
